<template>
  <div class="employees">
    <el-card class="top">
      <HmTip>
        <template #right>
          <div>
            <el-button
              type="primary"
              size="small"
              @click="outputExcel"
            >导出</el-button>
            <el-button
              type="primary"
              size="small"
              @click="importClick"
            >导入</el-button>
            <el-button
              type="primary"
              size="small"
              @click="addClick"
            >+新增员工</el-button>
          </div>
        </template>
      </HmTip>
    </el-card>
    <el-card>
      <el-table :data="list" border>
        <el-table-column label="序号" width="80px">
          <template v-slot="{ $index }">
            <div>
              {{ (page.page - 1) * page.size + $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable label="头像" prop="staffPhoto" width="80px">
          <template v-slot="{ row }">
            <img
              v-imgerror
              class="avatar"
              :src="row.staffPhoto"
              alt=""
              @click="imgClick(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column sortable label="姓名" prop="username" />
        <el-table-column sortable label="手机号" prop="mobile" />
        <el-table-column sortable label="工号" prop="workNumber" />
        <el-table-column
          sortable
          label="聘用形式"
          prop="formOfEmployment"
          @formatter="formatterEvent"
        >
          <template v-slot="{ row }">
            <div>
              <!-- 1.借助过滤器的方法 -->
              {{ row.formOfEmployment | formatStr }}
              <!-- 2.借助 element-ui 提供的组件方法进行转换 formatter -->
              <!-- 3.借助自定义指令 -->
              <!-- 4.从数据源头进行转换 -->
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable label="部门" prop="departmentName" />
        <el-table-column sortable label="入职时间" prop="timeOfEntry2" />
        <el-table-column sortable label="是否在职" prop="enableState2" />
        <el-table-column label="操作" fixed="right" width="300px">
          <template v-slot="{ row }">
            <div>
              <el-button
                type="text"
                @click="viewDetail(row.id)"
              >查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="roleClick(row.id)">角色</el-button>
              <!-- <el-button
                v-if="
                  $store.state.user.userInfo.roles.points.includes(
                    'employees_delBtn'
                  )
                "
                type="text"
                @click="del(row.id)"
              >删除</el-button> -->
              <el-button
                v-btnControl.inlineBlock="'employees_delBtn'"
                type="text"
                @click="del(row.id)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page="page.page"
          :page-sizes="[1, 5, 10, 100, 200, 300, 400]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增员工弹框组件 -->
    <!-- <Add :dialog-visible="show" @update:dialogVisible="show = $event" /> -->
    <Add :dialog-visible.sync="show" @getData="getData" />
    <!-- 二维码头像弹框 -->
    <el-dialog :visible.sync="qrcodeShow" title="头像二维码">
      <div style="text-align: center">
        <canvas ref="canvas" />
      </div>
    </el-dialog>
    <!-- 角色管理弹框组件 -->
    <Role ref="role" />
  </div>
</template>

<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import employeesObj from '@/api/constant/employees'
import Add from './components/add.vue'
import moment from 'moment'
// import { export_json_to_excel } from '@/vendor/Export2Excel'
import Qrcode from 'qrcode'
import Role from './components/Role.vue'
export default {
  components: {
    Add,
    Role
  },
  data() {
    return {
      qrcodeShow: false,
      show: false,
      list: [],
      page: {
        page: 1,
        size: +window.localStorage.getItem('employeesSize') || 1,
        total: 100
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      // 在职状态从数据源头进行转换
      res.data.rows.forEach((item) => {
        item.enableState2 = this.findState(item.enableState)
        item.timeOfEntry2 = moment(item.timeOfEntry).format('YYYY-MM-DD')
      })
      this.list = res.data.rows
      this.page.total = res.data.total
    },
    findState(id) {
      const resItem = employeesObj.workingState.find((item) => {
        return +item.id === id
      })
      return resItem ? resItem.value : '-'
    },
    formatterEvent(id) {
      const temp = employeesObj.hireType.find((item) => {
        return item.id === id
      })
      return temp ? temp.value : '-'
    },
    handleSizeChange(size) {
      this.page.size = size
      window.localStorage.setItem('employeesSize', size)
      this.page.page = 1
      this.getData()
    },
    handleCurrentChange(page) {
      this.page.page = page
      this.getData()
    },
    addClick() {
      this.show = true
    },
    del(id) {
      this.$confirm('你确定删除该条数据吗?', '提示')
        .then(async() => {
          await sysUserDelete(id)
          this.$message.success('删除成功')
          this.page.page = 1
          this.getData()
        })
        .catch(() => {})
    },
    // 导入点击事件
    importClick() {
      this.$router.push('/employees/import')
    },
    // 查看按钮点击
    viewDetail(id) {
      // 基本传参
      // this.$router.push('/employees/detail?id=' + id)
      // 动态路由匹配传参
      this.$router.push('/employees/detail/' + id)
    },
    // 点击导出excel文件
    async outputExcel() {
      const res = await sysUser({
        page: 1,
        size: 99999
      })
      const rules = {
        姓名: 'username',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry'
      }
      const header = Object.keys(rules)
      const data = res.data.rows.map((item) => {
        const newArr = []
        Object.values(rules).forEach((item2) => {
          if (item2 === 'timeOfEntry') {
            newArr.push(moment(item[item2]).format('YYYY-MM-DD'))
          } else if (item2 === 'formOfEmployment') {
            newArr.push(this.formatterEvent(item[item2]))
          } else {
            newArr.push(item[item2])
          }
        })
        return newArr
      })
      // 使用到导出时才进行引入该插件,这个xlsx与file-saver插件较大
      // 小优化,按需导入的处理方式
      import('@/vendor/Export2Excel').then((res) => {
        res.export_json_to_excel({
          header,
          data,
          filename: '员工列表'
        })
      })
    },
    // 头像点击生成二维码
    imgClick(imgUrl) {
      this.qrcodeShow = true
      // 头像地址不存在时就不渲染
      if (!imgUrl) {
        return
      }
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.canvas, imgUrl, {
          width: 300,
          height: 300
        })
      })
    },
    roleClick(id) {
      this.$refs.role.isShow = true
      // 获取该点击项的基本信息以拿到该点击项的角色Id集合
      this.$refs.role.getRoleIds(id)
    }
    // element-ui自带的方法
    // formatterForm(row, column, cellValue, index) {}
  }
}
</script>

<style lang="scss" scoped>
.employees {
  padding: 20px;
  .top {
    margin-bottom: 20px;
  }
  ::v-deep .top .el-card__body {
    padding: 10px;
  }
  .page {
    text-align: right;
    margin-top: 20px;
  }
  .avatar {
    width: 30px;
    height: 30px;
    object-fit: cover;
  }
}
</style>
